/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */
package toolcbc

import (
	"prim-server/config"

	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/global"
	iam "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iam/v3"
	iamModel "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iam/v3/model"
	iamRegion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iam/v3/region"
)

const (
	identifyMethod          = "assume_role"
	identifyDurationSeconds = int32(15 * 60) //临时认证有效期，取最小值，15分钟过期
	emptyString             = ""
)

var (
	iamAK      = config.GetConfig().BSSConfig.AK
	iamSK      = config.GetConfig().BSSConfig.SK
	agencyName = config.GetConfig().BSSConfig.XAccountType
)

var iamClient *iam.IamClient

func getIAMClient() *iam.IamClient {
	if iamClient == nil {
		auth := global.NewCredentialsBuilder().
			WithAk(iamAK).
			WithSk(iamSK).
			Build()
		iamClient = iam.NewIamClient(
			iam.IamClientBuilder().
				WithRegion(iamRegion.ValueOf("cn-north-4")).
				WithCredential(auth).
				Build())
	}
	return iamClient
}

// 获取子账户临时凭证
func getTempSubClientCredential(domainIdAssumeRole string) (*iamModel.CreateTemporaryAccessKeyByAgencyResponse, error) {
	client := getIAMClient()
	request := &iamModel.CreateTemporaryAccessKeyByAgencyRequest{}
	durationSec := identifyDurationSeconds
	assumeRoleIdentity := &iamModel.IdentityAssumerole{
		AgencyName:      agencyName,
		DomainId:        &domainIdAssumeRole,
		DurationSeconds: &durationSec,
	}
	var listMethodsIdentity = []iamModel.AgencyAuthIdentityMethods{
		iamModel.GetAgencyAuthIdentityMethodsEnum().ASSUME_ROLE,
	}
	identityAuth := &iamModel.AgencyAuthIdentity{
		Methods:    listMethodsIdentity,
		AssumeRole: assumeRoleIdentity,
	}
	authBody := &iamModel.AgencyAuth{
		Identity: identityAuth,
	}
	request.Body = &iamModel.CreateTemporaryAccessKeyByAgencyRequestBody{
		Auth: authBody,
	}
	response, err := client.CreateTemporaryAccessKeyByAgency(request)
	if err != nil {
		return nil, err
	}
	return response, nil
}

// 获取子账户临时AKSK
func getTempSubClientAKSK(cloudUserId string) (tempAK, tempSK, tempSecurityToken string, err error) {
	credential, err := getTempSubClientCredential(cloudUserId)
	if err != nil {
		return emptyString, emptyString, emptyString, err
	}
	return credential.Credential.Access, credential.Credential.Secret, credential.Credential.Securitytoken, nil
}
